#include "HttpServer.hpp"

using namespace LogModule;

void Login(HttpRequest &req, HttpResponse &resp, HttpServer &server)
{
    // 根据req，动态构建resp usename=xxx&password=xxx
    LOG(LogLevel::DEBUG) << "进入到登录模块" << req.Path() << "," << req.Args();
    std::string req_args = req.Args();

    // 1.获取sessionid，判断是否登录过
    static int number = 0;
    std::string sessionid = req.SessionId();
    if(sessionid.empty()) //说明历史没有登陆过
    {
        std::string user = "user-" + std::to_string(number++);
        session_ptr sess_ptr = std::make_shared<Session>(user, "logined");
        sessionid = server.AddSession(sess_ptr);
        LOG(LogLevel::DEBUG) << user << "被添加, sessionid是" << sessionid;
        resp.SetHeader("Set-Cookie", "sessionid=" + sessionid + ";");
    }

    LOG(LogLevel::DEBUG) << server.DebugPrint();

    // 2.解析参数格式，得倒要的参数
    // 3. 访问数据库，验证对应的用户是否为合法用户
    // 4.登录成功
    std::string body = req.Get_Content("wwwroot/success.html");
    resp.SetBody(body);
    resp.SetCode(200);
    resp.SetHeader("Content-Length", std::to_string(body.size()));
    resp.SetHeader("Content-Type", "text/html");
    //resp.SetHeaderFromVector(cookie_key, "username=zhangsan");

    // resp.SetCode(302);
    // resp.SetHeader("Location", "/");
}

void Register(HttpRequest &req, HttpResponse &resp, HttpServer &server)
{
    // 根据req，动态构建resp
    LOG(LogLevel::DEBUG) << "进入到注册模块" << req.Path() << "," << req.Args();

}

void Search(HttpRequest &req, HttpResponse &resp, HttpServer &server)
{
    // 根据req，动态构建resp
    LOG(LogLevel::DEBUG) << "进入到搜索模块" << req.Path() << "," << req.Args();

}

void Test(HttpRequest &req, HttpResponse &resp, HttpServer &server)
{
    // 根据req，动态构建resp
    LOG(LogLevel::DEBUG) << "进入到测试模块" << req.Path() << "," << req.Args();

}

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        std::cout << "Usage: " << argv[0] << " port" << std::endl;
        return 1;
    }

    auto httpserver = std::make_shared<HttpServer>(std::stoi(argv[1]));

    // 要让服务器有登录功能，需要在这里注册登录的处理函数
    httpserver->Register("/login", Login);  // restful风格的网络接口
    httpserver->Register("/register", Register );
    httpserver->Register("/search", Search);
    httpserver->Register("/test", Test);

    httpserver->Start();
    return 0;
}